package com.caldremch.calhttp.http;

import android.text.TextUtils;
import com.alibaba.fastjson.JSON;
import com.caldremch.calhttp.http.base.BaseResp;
import com.caldremch.calhttp.http.base.BaseRespData;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import io.reactivex.functions.Function;

/**
 * @author Caldremch
 * @date 2018-01-19 23:24
 * @describe
 **/
public abstract class MapConvert<T> implements Function<BaseResp, BaseRespData<T>> {

    @Override
    public BaseRespData<T> apply(BaseResp baseResp) throws Exception {
        Type t = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        BaseRespData<T> data = new BaseRespData<>();
        data.code = baseResp.code;
        data.msg = baseResp.msg;
        data.serverTime = baseResp.serverTime;
        data.data = null;
        //服务端返回的 data 为 null 或者 是对象是空的
        if (!TextUtils.isEmpty(baseResp.data)) {
            try {
                data.data = JSON.parseObject(baseResp.data, pt.getActualTypeArguments()[0]);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return data;
    }
}
